package org.product.ueditor;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author zqx
 * @date 2021-01-13
 */
@WebServlet("/news/add.do")
public class AddNewsServlet extends HttpServlet {

    private String readFile(String filename) {
        String neiRong = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            // 第一：建立联系，选择要操作文件
            File f = new File(filename);


            // 第二：选择流对象(管道)　 -> 创建流对象
            fis = new FileInputStream(f);
            isr = new InputStreamReader(fis);

            //InputStreamReader isr = new InputStreamReader(fis,"gbk") ;
            br = new BufferedReader(isr);

            // 第三：操作-读 -> 调用流对象的方法
            String str = null;
            while ((str = br.readLine()) != null) {
                neiRong += str;
            }
            // 第四：关闭流，释放资源

        } catch (Exception e) {

        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return neiRong;
    }

    private void writeFile(File outFile, String content) {
        try {
            // 第二：选择流对象(管道)　 -> 创建流对象
            // 节点流
            OutputStream os = new FileOutputStream(outFile, false);
            // 处理流
            BufferedOutputStream bos = new BufferedOutputStream(os);

            // 第三：读/写 -> 调用流对象的方法
            // 1.编码
            byte[] data = content.getBytes();
            // 2.写
            FileWriter fw = new FileWriter(outFile);

            bos.write(data, 0, data.length);

            // 第四：关闭流，释放资源
            bos.close();
            fw.flush();
            fw.close();
        } catch (Exception e) {

        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        String path = req.getServletContext().getRealPath("/");

        String filePath = path + "test.html";

        String neiRong = readFile(filePath);

        File outFile = new File(path + UUID.randomUUID() + ".html");

        String content = req.getParameter("content");

        neiRong = neiRong.replace("####content####", content);

        writeFile(outFile, neiRong);
    }
}
